# -*- coding = utf-8 -*-
# @Time    : 2025/4/1 上午11:26
# @Author  : yqk
# @File    : 滑块登录.py
# @Software: PyCharm
import random
import time
# 登录豆瓣
import pyautogui
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from random import randint
from random import uniform
import os
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from CalculateDistance import CalculateDistance

def press_button():
    pic_addr = r'D:\python-code\chaojiying_Python\img\douban2.png'
    loc = pyautogui.locateOnScreen(pic_addr)
    p = pyautogui.center(loc)
    pyautogui.moveTo(p)
    pyautogui.leftClick()


def handle_distance(distance):
    """
    将直线距离转换为缓慢的轨迹，即生成一系列逐渐增大的步长。

    :param distance: 总直线距离，单位为像素或其他长度单位。
    :return: 包含一系列步长的列表，步长逐渐增大。
    """
    slow_distance = []
    current_distance = 0

    while current_distance < distance:
        # 随机生成一个步长，范围在-2到15之间
        step = random.randint(-2, 15)
        # 确保总距离不超过目标距离
        if current_distance + step > distance:
            step = distance - current_distance
        # 更新当前距离
        current_distance += step
        # 将步长添加到列表
        slow_distance.append(step)

    # 如果总距离与目标距离不一致，调整最后一个步长
    if sum(slow_distance) != distance:
        slow_distance.append(distance - sum(slow_distance))

    return slow_distance


def drag_slide(tracks, slide_addr):
    """
    模拟拖动滑块的操作。
    :param tracks: 滑动轨迹的位移列表。
    :param slide_addr: 滑块图片的文件路径，用于定位滑块位置。
    """
    # 定位滑块在屏幕上的位置
    loc = pyautogui.locateOnScreen(slide_addr)

    p1 = pyautogui.center(loc)
    # 移动鼠标到滑块位置
    pyautogui.moveTo(p1)
    # 按下鼠标左键
    pyautogui.mouseDown()
    # 遍历轨迹，模拟滑动
    for track in tracks:
    # 随机扰动，模拟人类操作
        pyautogui.move(track, random.uniform(-2, 2), duration=0.15)
    # 松开鼠标左键
    pyautogui.mouseUp()
def login(url, username, password,path):
    service = Service(executable_path='D:\python-code\chromedriver-win64\chromedriver.exe')
    opt = Options()
    opt.debugger_address = "127.0.0.1:8888"

    # 初始化 WebDriver
    browser = webdriver.Chrome(service=service, options=opt)
    # opt = Options()
    # opt.add_argument('--disable-blink-features=AutomationControlled')
    # opt.page_load_strategy = 'normal' # 默认是normal，normal：等待页面完全加载完成，eager：等待页面基本加载完成，interactive：等待页面基本加载完成，但是不加载图片，css，js等资源，这个性能最好，但是页面加载速度会慢一点
    browser.implicitly_wait(5)
    browser.get(url)
    time.sleep(3)
    iframe = browser.find_element(By.XPATH, '//*[@id="anony-reg-new"]/div/div[1]/iframe')
    browser.switch_to.frame(iframe)
    browser.find_element(By.XPATH, '/html/body/div[1]/div[1]/ul[1]/li[2]').click()
    browser.find_element(By.XPATH, '//*[@id="username"]').send_keys(username)
    time.sleep(2)
    browser.find_element(By.XPATH, '//*[@id="password"]').send_keys(password)
    time.sleep(1)
    press_button()
    time.sleep(3)
    # 进入验证码
    WebDriverWait(browser, 6).until(EC.presence_of_element_located((By.ID, 'tcaptcha_iframe_dy')))
    slide_frame = browser.find_element(By.ID , 'tcaptcha_iframe_dy')
    browser.switch_to.frame(slide_frame)
    # browser.switch_to.default_content()  # 退回·到访问iframe标签外的元素
    # 获取背景图片
    bg_pic = browser.find_element(By.ID, 'slideBg')
    bg_pic_location = bg_pic.location
    print(bg_pic_location)
    bc_img = bg_pic.screenshot_as_png
    fliename = int(time.time())
    with open(f'{path}/{fliename}.png', 'wb') as f:
        f.write(bc_img)
        print('已下载背景图片')
    # 获取滑动图片
    slide_pic1 = browser.find_element(By.XPATH, '//*[@id="tcOperation"]/div[7]')
    slide_pic2 = browser.find_element(By.XPATH, '//*[@id="tcOperation"]/div[8]')
    s1 = slide_pic1.size
    s2 = slide_pic2.size
    print(s1, s2)
    if s1['width'] > 100 and s1['height'] < 20:
        slide_element = slide_pic2
    else:
        slide_element = slide_pic1
    slide_pic_location = slide_element.location
    print(slide_pic_location)
    slide_img = slide_element.screenshot_as_png
    with open(f'{path}/SD-{fliename}.png', 'wb') as f:
        f.write(slide_img)
        print('已下载滑动图片')
    #背景图片和滑块地址图片的地址
    bg_addr = f'{path}/{fliename}.png'
    slide_addr = f'{path}/SD-{fliename}.png'
    #计算背景图片和滑块图片的x距离
    x_distance = slide_pic_location['x'] - bg_pic_location['x']
    y_distance = slide_pic_location['y'] - bg_pic_location['y']
    print(x_distance, y_distance)
    slide_offset = CalculateDistance(bg_addr, slide_addr, x_distance, y_distance,1)
    slide_offset = slide_offset.run()
    print(slide_offset)
    # tracks = handle_distance(slide_offset)
    # slide_img_address = r'D:\python-code\chaojiying_Python\img\douban_silde.png'
    # drag_slide(tracks, slide_img_address)

if __name__ == '__main__':
    url = 'https://www.douban.com/'
    path = 'D:\python-code\chaojiying_Python\img'
    username = '1223556516516'
    password = '156165165'
    login(url, username, password, path)

